package com.zw.mizhe.api;

import android.content.Context;
import android.text.TextUtils;

import com.cpoopc.retrofitrxcache.BasicCache;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zw.mizhe.App;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zhangwei on 16/10/21.
 */
public class RetrofitManager {
    private static volatile RetrofitManager instance = null;
    private static final long REASONABLE_DISK_SIZE = 1024 * 1024; // 1 MB
    private static final int REASONABLE_MEM_ENTRIES = 50; // 50 entries
    private Gson gson;
    private Retrofit retrofit;
    private static final String DEFAULT_RX_CACHE = "rxCache";
    private OkHttpClient okHttpClient;
    private LinkedHashMap<String, Retrofit> hashMap = new LinkedHashMap<>();


    private RetrofitManager() {
        initGson();
        initOkhttp(App.getInstance());
    }

    public static RetrofitManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }

    private void initOkhttp(final Context context) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //打印请求log日志
//        if (BuildConfig.DEBUG) {
//            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
//            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//            builder.addInterceptor(loggingInterceptor);
//        }
        //设置缓存 默认开启
        File cacheFile = new File(context.getExternalCacheDir(), DEFAULT_RX_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
//        Interceptor cacheInterceptor = new CacheInterceptor(context, true);
        builder.cache(cache);
//        builder.interceptors().add(cacheInterceptor);//添加本地缓存拦截器，用来拦截本地缓存
//        builder.networkInterceptors().add(cacheInterceptor);//添加网络拦截器，用来拦截网络数据
//        builder.addInterceptor(HeaderInterceptor );
        //设置超时
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        //添加cookie
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
        builder.cookieJar(cookieJar);

        okHttpClient = builder.build();

    }


    private void initGson() {
        gson = new GsonBuilder()
                .serializeNulls()
//                .setDateFormat("yyyy-MM-dd hh:mm:ss")
                .create();
    }

    public Retrofit getRetrofit(String baseUrl) {
        String url = !TextUtils.isEmpty(baseUrl) ? baseUrl : UrlManager.RequestUrl.BASE_URL;
        if (hashMap.get(url) == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(okHttpClient)
//                    .addCallAdapterFactory(RxCacheCallAdapterFactory.create(getBaseCache(), false))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
            hashMap.put(baseUrl, retrofit);
        }
        return retrofit;
    }

    public Retrofit getRetrofit() {
        return this.getRetrofit(null);
    }

    /**
     * 设置缓存路径 缓存大小
     *
     * @return BasicCache
     */

    private BasicCache getBaseCache() {
        return new BasicCache(
                new File(App.getInstance().getExternalCacheDir(), DEFAULT_RX_CACHE),
                REASONABLE_DISK_SIZE,
                REASONABLE_MEM_ENTRIES);
    }


//
//    public static class Builder {
//        private boolean isUseCache = true;
//        private Gson gson;
//        private static final String DEFAULT_RX_CACHE = "rxCache";
//        private OkHttpClient okHttpClient;
//
//        public boolean isUseCache() {
//            return isUseCache;
//        }
//
//        public void setUseCache(boolean useCache) {
//            isUseCache = useCache;
//        }
//
//        public Gson getGson() {
//            return gson;
//        }
//
//        public void setGson(Gson gson) {
//            this.gson = gson;
//        }
//
//        public static String getDefaultRxCache() {
//            return DEFAULT_RX_CACHE;
//        }
//
//        public OkHttpClient getOkHttpClient() {
//            return okHttpClient;
//        }
//
//        public void setOkHttpClient(OkHttpClient okHttpClient) {
//            this.okHttpClient = okHttpClient;
//        }
//    }


}